package com.itheima.web.manager;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.domain.db.Admin;
import com.itheima.service.db.AdminService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import com.itheima.web.exception.BusinessException;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Component
public class AdminManager {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @DubboReference
    AdminService adminService;

    public LineCaptcha verification(String uuid) {
        //1.调用hutool中方法生成验证码图片
        LineCaptcha lineCaptcha = new LineCaptcha(200, 100);

        //2.将验证码存入redis中且时效5分钟
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_CODE+uuid,lineCaptcha.getCode(), Duration.ofMinutes(5));

        //3.返回验证码图片
        return lineCaptcha;
    }

    public ResponseEntity login(String username, String password, String verificationCode, String uuid) {
        //1.判断用户输入的验证码是否正确
        String redisCode = stringRedisTemplate.opsForValue().get(ConstantUtil.ADMIN_CODE + uuid);

        //1.1若错误,使用自定义异常提示
        if (!StrUtil.equalsIgnoreCase(redisCode,verificationCode)) {
            throw new BusinessException("验证码输入错误~~");
        }

        //2.远程调用service,通过用户名查询
        Admin admin = adminService.findByUsername(username);

        //2.1若找不到用户,使用自定义异常提示
        if (null == admin) {
            throw new BusinessException("用户名输入错误~~");
        }

        //3.继续判断密码是否正确,若不正确提示
        if (!StrUtil.equals(admin.getPassword(), SecureUtil.md5(password))) {
            throw new BusinessException("密码输入错误~~");
        }

        //4.生成token
        admin.setPassword(null);
        String token = JwtUtil.createToken(BeanUtil.beanToMap(admin));

        //5.将token放入redis中且设置时效1个小时, key:token value:用户json数据
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_TOKEN+token, JSON.toJSONString(admin),Duration.ofHours(1));

        //6.返回json数据,包含token
        Map map = new HashMap();
        map.put("token",token);
        return ResponseEntity.ok(map);
    }

    public ResponseEntity logout(String token) {
        //处理token
        token = token.replaceAll("Bearer ", "");

        //删除redis中token
        stringRedisTemplate.delete(ConstantUtil.ADMIN_TOKEN+token);
        return ResponseEntity.ok(null);
    }
}
